
#include <png.h>

#include "color.h"
#include "image.h"

static int check_valid_pixel (geopoint_image_t *image, int x, int y)
{
    return 0;
}

void geopoint_image_init (geopoint_image_t *image)
{
    
}

void geopoint_image_free (geopoint_image_t *image)
{
    
}

int geopoint_image_set_pixel (geopoint_image_t *image, int x, int y,
    geopoint_color_t *color)
{
    if (check_valid_pixel (image, x, y) < 0) {
        return -1;
    }
}

int geopoint_image_save_as_png (geopoint_image_t *image, char *filename)
{
    FILE *fp;
    png_structp png_ptr;
    png_infop info_ptr;
    int i, j;
    
    fp = fopen (filename, "wb");
    if (fp == NULL) {
        return -1;
    }
    
    /* create the png write data structure
     */
    png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING,
        NULL, NULL, NULL);
    if (png_ptr == NULL) {
        fclose (fp);
        return -1;
    }
    
    png_set_filter (png_ptr, 0, PNG_FILTER_NONE);
    
    /* create the png info data structure
     */
    info_ptr = png_create_info_struct (png_ptr);
    if (info_ptr == NULL) {
        fclose (fp);
        png_destroy_write_struct (&png_ptr, png_infopp_NULL);
        return -1;
    }
    
    if (setjmp(png_jmpbuf(png_ptr))) {
        fclose (fp);
        png_destroy_write_struct (&png_ptr, &info_ptr);
        return -1;
    }
    
    /* initialize the png IO
     */
    png_init_io (png_ptr, fp);
    png_set_IHDR (png_ptr, info_ptr, image->width, image->height, 8,
        PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
        PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
    
    /* write the image data to the png
     */
    png_bytep rows[800][600];
    
    png_write_info (png_ptr, info_ptr);
    for (i = 0; i < image->height; i++) {
        for (j = 0; j < image->width; j++) {
            rows[i][j] = (png_bytep) 0x000000ff;
        }
        
        png_write_row (png_ptr, (png_bytep) rows[i]);
    }
    
    /* clean up
     */
    png_write_end (png_ptr, info_ptr);
    png_destroy_write_struct (&png_ptr, &info_ptr);
    fclose (fp);
    return 0;
}

int geopoint_image_save_as_jpg (geopoint_image_t *image, char *filename)
{
    FILE *fp;
}
